package com.javasm.mingming.common.utils;

import com.alibaba.fastjson2.JSONObject;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.util.StringUtils;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;

/**
 * @author javasm
 * @version 0.1
 * @className RequestBodyUtil
 * @descriptioin:
 * @date 2025/1/13 14:52
 * @since jdk11
 */
public class RequestBodyUtil {

    public static Map<String,String> read(HttpServletRequest request){
        try {
            //从Request中 获取字节流
            ServletInputStream inputStream = request.getInputStream();
            //字节流转成字节流字符流转换对象
            InputStreamReader streamReader = new InputStreamReader(inputStream);
            //字符流
            BufferedReader reader = new BufferedReader(streamReader);
            StringBuilder json = new StringBuilder();
            String line;
            while ((line=reader.readLine()) != null){
                json.append(line).append("\n");
            }
            String jsonStr = json.toString().trim();
            if (StringUtils.isEmpty(jsonStr)){
                throw new AuthenticationServiceException("参数为空,没有传json数据");
            }
            //json字符串转成map
            Map<String,String> map = JSONObject.parseObject(jsonStr,Map.class);
            return map;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
